package com.wedo.mall.fragment;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.e.library.entity.User;
import com.e.library.fragment.EFragment;
import com.e.library.http.EApi;
import com.e.library.http.EClient;
import com.e.library.http.EObserver;
import com.e.library.http.EResponse;
import com.e.library.utils.ESPUtils;
import com.e.library.widget.EBadgeView;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.wedo.mall.R;
import com.wedo.mall.activity.LoginActivity;
import com.wedo.mall.activity.MainActivity;
import com.wedo.mall.activity.login.WLogin;
import com.wedo.mall.activity.register.RegisterActivity;
import com.wedo.mall.activity.user.MessageActivity;
import com.wedo.mall.activity.user.MyAddressActivity;
import com.wedo.mall.activity.user.MyCollectionActivity;
import com.wedo.mall.activity.user.MyIntegralActivity;
import com.wedo.mall.activity.user.MyOrderActivity;
//import com.wedo.mall.activity.user.MyWalletActivity;
import com.wedo.mall.activity.user.PersonalDataActivity;
import com.wedo.mall.activity.user.PurchaseRecordActivity;
//import com.wedo.mall.activity.user.RecommendPrize2Activity;
import com.wedo.mall.activity.user.RecommendPrizeActivity;
import com.wedo.mall.activity.user.SettingActivity;
import com.wedo.mall.activity.user.WalletDetailActivity;
import com.wedo.mall.entity.UserIndex;
import com.wedo.mall.util.WUrl;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.wedo.mall.activity.login.WLogin.USER;

/**
 * Created by lxy on 2017/6/8.
 */

public class UserFragment extends EFragment<MainActivity> implements EMMessageListener{

    @BindView(R.id.iv_user_bg) ImageView iv_user_bg;

    @BindView(R.id.ll_un_login) LinearLayout ll_un_login;
    @BindView(R.id.rl_head_login) RelativeLayout rl_head_login;
    @BindView(R.id.eim_portrait) ImageView eim_portrait;
    @BindView(R.id.tv_username) TextView tv_username;

    @BindView(R.id.tv_unpaid) TextView tv_unpaid;
    @BindView(R.id.tv_unprocessed) TextView tv_unprocessed;
    @BindView(R.id.tv_notreceived) TextView tv_notreceived;
    @BindView(R.id.tv_pendingevaluation) TextView tv_pendingevaluation;

    @BindView(R.id.rl_wallet) RelativeLayout rl_wallet;
    @BindView(R.id.rl_integral) RelativeLayout rl_integral;
    @BindView(R.id.rl_recommend) RelativeLayout rl_recommend;
    @BindView(R.id.tv_balance) TextView tv_balance;

    @BindView(R.id.iv_usermessage) ImageView iv_usermessage;

    EBadgeView UnpaidBadgeView,UnprocessedBadgeView,NotreceivedBadgeView,PendingevaluationBadgeView;
    EBadgeView mUnreadBadge;

    public static UserFragment with(){
        return new UserFragment();
    }
    @Override
    protected int layout() {
        return R.layout.fragment_user;
    }

    @Override
    protected void onFragmentCreated(View contentView, Bundle bundle) {

        fixUserBGHeight();
        init();

    }

    /**
     * 动态适配头部背景图片高度
     */
    private void fixUserBGHeight(){
        BitmapFactory.Options options = new BitmapFactory.Options();
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.user_bg, options);
        //获取bitmap的宽度
        float bitWidth = bitmap.getWidth();
        //获取bitmap的宽度
        float bitheight = bitmap.getHeight();
        //计算出图片的高宽比，然后按照图片的比列去缩放图片
        float bitScale =  bitheight / bitWidth;
        //获取屏幕宽度
        WindowManager wm = getActivity().getWindowManager();
        int screenWidth = wm.getDefaultDisplay().getWidth();

        ViewGroup.LayoutParams  lp = iv_user_bg.getLayoutParams();
        //设置imageView宽
        lp.height =  (int)(screenWidth * bitScale);
        iv_user_bg.setLayoutParams(lp);
    }

    private void init(){
        UnpaidBadgeView = new EBadgeView(activity());
        UnpaidBadgeView.setTargetView(tv_unpaid);
        UnpaidBadgeView.setBadgeMargin(0,0,20,0);

        UnprocessedBadgeView = new EBadgeView(activity());
        UnprocessedBadgeView.setTargetView(tv_unprocessed);
        UnprocessedBadgeView.setBadgeMargin(0,0,20,0);

        NotreceivedBadgeView = new EBadgeView(activity());
        NotreceivedBadgeView.setTargetView(tv_notreceived);
        NotreceivedBadgeView.setBadgeMargin(0,0,20,0);

        PendingevaluationBadgeView = new EBadgeView(activity());
        PendingevaluationBadgeView.setTargetView(tv_pendingevaluation);
        PendingevaluationBadgeView.setBadgeMargin(0,0,20,0);

        mUnreadBadge = new EBadgeView(getContext());
        mUnreadBadge.setTargetView(iv_usermessage);
        PendingevaluationBadgeView.setBadgeMargin(0,0,20,0);
    }

    /**
     * 获取个人信息
     */
    private void getUserInfo(){
        EClient.with().post(EApi.USER_INFO, new EObserver() {
            @Override
            public void successful(EResponse response) {
                User user = response.object("list",User.class);
                tv_balance.setText(user.money);
                WLogin.saveUser(activity(),user);
            }

            @Override
            public void failure(String msg) {
            }
        });
    }

    /**
     * 个人中心首页
     */
    private void getUserIndex(){
        EClient.with().post(EApi.USER_INDEX, new EObserver() {
            @Override
            public void successful(EResponse response) {
                UserIndex userIndex = response.object("list",UserIndex.class);
                UnpaidBadgeView.setBadgeCount(Integer.valueOf(userIndex.order.pay));
                UnprocessedBadgeView.setBadgeCount(Integer.valueOf(userIndex.order.delivery));
                NotreceivedBadgeView.setBadgeCount(Integer.valueOf(userIndex.order.receive));
                PendingevaluationBadgeView.setBadgeCount(Integer.valueOf(userIndex.order.comment));
            }

            @Override
            public void failure(String msg) {

            }
        });
    }

    /**未读消息数*/
    private void unread() {

        iv_usermessage.post(new Runnable() {
            @Override
            public void run() {
                int count = EMClient.getInstance().chatManager().getUnreadMessageCount();
                mUnreadBadge.setBadgeCount(count);
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        tv_balance.setText("");
        if (WLogin.logged(this)){
            User user = WLogin.user();
            ll_un_login.setVisibility(View.GONE);
            rl_head_login.setVisibility(View.VISIBLE);
            tv_username.setText(user.nickname);
            Glide.with(this).load(WUrl.url(user.headimgurl)).error(R.drawable.ease_default_avatar).placeholder(R.drawable.ease_default_avatar).diskCacheStrategy(DiskCacheStrategy.ALL).into(eim_portrait);

            getUserInfo();
            getUserIndex();

            unread();

            EMClient.getInstance().chatManager().addMessageListener(this);

        }else {
            rl_head_login.setVisibility(View.GONE);
            ll_un_login.setVisibility(View.VISIBLE);
            UnpaidBadgeView.setBadgeCount(0);
            UnprocessedBadgeView.setBadgeCount(0);
            NotreceivedBadgeView.setBadgeCount(0);
            PendingevaluationBadgeView.setBadgeCount(0);
            mUnreadBadge.setBadgeCount(0);

            EMClient.getInstance().chatManager().removeMessageListener(this);
        }

    }

    @Override
    public void onStop() {
        super.onStop();
        EMClient.getInstance().chatManager().removeMessageListener(this);
    }

    @OnClick(R.id.iv_usermessage)
    protected void onMessageClick(){
        if (WLogin.logged(this)){
            activity().toActivity(MessageActivity.class);
        }else {
            Bundle bundle = new Bundle();
            bundle.putInt(LoginActivity.EXTRA_ENDPOINT,LoginActivity.ENDPOINT_MAIN);
            activity().toActivity(LoginActivity.class,bundle);
        }
    }

    @OnClick(R.id.eim_portrait)
    protected void onPortraitClick(){
        activity().toActivity(PersonalDataActivity.class);
    }

    @OnClick(R.id.iv_setting)
    protected void onSettingClick(){
        if (WLogin.logged(this)){
            activity().toActivity(SettingActivity.class);
        }else {
            Bundle bundle = new Bundle();
            bundle.putInt(LoginActivity.EXTRA_ENDPOINT,LoginActivity.ENDPOINT_MAIN);
            activity().toActivity(LoginActivity.class,bundle);
        }
    }

    //@OnClick(R.id.rl_wallet)
    protected void onMyWalletClick(){
        if (WLogin.logged(this)){
            //activity().toActivity(MyWalletActivity.class);
            activity().toActivity(WalletDetailActivity.class);
        }else {
            Bundle bundle = new Bundle();
            bundle.putInt(LoginActivity.EXTRA_ENDPOINT,LoginActivity.ENDPOINT_MAIN);
            activity().toActivity(LoginActivity.class,bundle);
        }
    }

    @OnClick(R.id.rl_integral)
    protected void onMyIntegralClick(){
        if (WLogin.logged(this)){
            activity().toActivity(MyIntegralActivity.class);
        }else {
            Bundle bundle = new Bundle();
            bundle.putInt(LoginActivity.EXTRA_ENDPOINT,LoginActivity.ENDPOINT_MAIN);
            activity().toActivity(LoginActivity.class,bundle);
        }
    }

    @OnClick(R.id.rl_collection2)
    protected void onMyCollectionClick(){
        if (WLogin.logged(this)){
            activity().toActivity(MyCollectionActivity.class);
        }else {
            Bundle bundle = new Bundle();
            bundle.putInt(LoginActivity.EXTRA_ENDPOINT,LoginActivity.ENDPOINT_MAIN);
            activity().toActivity(LoginActivity.class,bundle);
        }
    }

    @OnClick(R.id.btn_login)
    protected void onLoginClick(){
        Bundle bundle = new Bundle();
        bundle.putInt(LoginActivity.EXTRA_ENDPOINT,LoginActivity.ENDPOINT_MAIN);
        activity().toActivity(LoginActivity.class,bundle);
    }

    @OnClick(R.id.btn_register)
    protected void onRegisterClick(){
        activity().toActivity(RegisterActivity.class);

    }

    @OnClick(R.id.rl_deliveryaddress)
    protected void onDeliveryAddressClick(){
        if (WLogin.logged(this)){
            Bundle bundle = new Bundle();
            bundle.putInt("endpoint",1);
            activity().toActivity(MyAddressActivity.class,bundle);
        }else {
            Bundle bundle = new Bundle();
            bundle.putInt(LoginActivity.EXTRA_ENDPOINT,LoginActivity.ENDPOINT_MAIN);
            activity().toActivity(LoginActivity.class,bundle);
        }
    }

    @OnClick(R.id.rl_purchaserecord)
    protected void onPurchaseRecordClick(){
        if (WLogin.logged(this)){
            activity().toActivity(PurchaseRecordActivity.class);
        }else {
            Bundle bundle = new Bundle();
            bundle.putInt(LoginActivity.EXTRA_ENDPOINT,LoginActivity.ENDPOINT_MAIN);
            activity().toActivity(LoginActivity.class,bundle);
        }
    }

    @OnClick(R.id.rl_myorder)
    protected void onMyOrderAll(){
        if (WLogin.logged(this)){
            Bundle bundle = new Bundle();
            bundle.putInt(MyOrderActivity.ORDER_SORT,MyOrderActivity.SORT_ALL);
            activity().toActivity(MyOrderActivity.class,bundle);
        }else {
            Bundle bundle = new Bundle();
            bundle.putInt(LoginActivity.EXTRA_ENDPOINT,LoginActivity.ENDPOINT_MAIN);
            activity().toActivity(LoginActivity.class,bundle);
        }
    }

    @OnClick(R.id.tv_unpaid)
    protected void onMyOrderUnpaid(){
        if (WLogin.logged(this)){
            Bundle bundle = new Bundle();
            bundle.putInt(MyOrderActivity.ORDER_SORT,MyOrderActivity.SORT_UNPAID);
            activity().toActivity(MyOrderActivity.class,bundle);
        }else {
            Bundle bundle = new Bundle();
            bundle.putInt(LoginActivity.EXTRA_ENDPOINT,LoginActivity.ENDPOINT_MAIN);
            activity().toActivity(LoginActivity.class,bundle);
        }
    }

    @OnClick(R.id.tv_unprocessed)
    protected void onMyOrderUnprocessed(){
        if (WLogin.logged(this)){
            Bundle bundle = new Bundle();
            bundle.putInt(MyOrderActivity.ORDER_SORT,MyOrderActivity.SORT_UNPROCESSED);
            activity().toActivity(MyOrderActivity.class,bundle);
        }else {
            Bundle bundle = new Bundle();
            bundle.putInt(LoginActivity.EXTRA_ENDPOINT,LoginActivity.ENDPOINT_MAIN);
            activity().toActivity(LoginActivity.class,bundle);
        }
    }

    @OnClick(R.id.tv_notreceived)
    protected void onMyOrderNotreceived(){
        if (WLogin.logged(this)){
            Bundle bundle = new Bundle();
            bundle.putInt(MyOrderActivity.ORDER_SORT,MyOrderActivity.SORT_NOTRECEIVED);
            activity().toActivity(MyOrderActivity.class,bundle);
        }else {
            Bundle bundle = new Bundle();
            bundle.putInt(LoginActivity.EXTRA_ENDPOINT,LoginActivity.ENDPOINT_MAIN);
            activity().toActivity(LoginActivity.class,bundle);
        }
    }

    @OnClick(R.id.tv_pendingevaluation)
    protected void onMyOrderPendingevaluation(){
        if (WLogin.logged(this)){
            Bundle bundle = new Bundle();
            bundle.putInt(MyOrderActivity.ORDER_SORT,MyOrderActivity.SORT_PENDINGEVALUATION);
            activity().toActivity(MyOrderActivity.class,bundle);
        }else {
            Bundle bundle = new Bundle();
            bundle.putInt(LoginActivity.EXTRA_ENDPOINT,LoginActivity.ENDPOINT_MAIN);
            activity().toActivity(LoginActivity.class,bundle);
        }
    }

    @OnClick(R.id.rl_recommend)
    protected void onRecommendClick(){
        if (WLogin.logged(this)){
            activity().toActivity(RecommendPrizeActivity.class);
            //activity().toActivity(RecommendPrize2Activity.class);
        }else {
            Bundle bundle = new Bundle();
            bundle.putInt(LoginActivity.EXTRA_ENDPOINT,LoginActivity.ENDPOINT_MAIN);
            activity().toActivity(LoginActivity.class,bundle);
        }
    }

    @Override
    public void onMessageReceived(List<EMMessage> list) {
        unread();
    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> list) {

    }

    @Override
    public void onMessageRead(List<EMMessage> list) {

    }

    @Override
    public void onMessageDelivered(List<EMMessage> list) {

    }

    @Override
    public void onMessageRecalled(List<EMMessage> list) {

    }

    @Override
    public void onMessageChanged(EMMessage emMessage, Object o) {

    }
}
